package com.check.checksamejourney.controller;


import com.check.checksamejourney.bean.User;
import com.check.checksamejourney.mapper.UserMapper;
import com.check.checksamejourney.response.BaseResponse;
import com.check.checksamejourney.response.ResponseState;
import com.check.checksamejourney.response.UserLoginResult;
import com.check.checksamejourney.util.WxappUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    UserMapper userMapper;

    @GetMapping("/login")
    public BaseResponse<UserLoginResult> login (String code){
        BaseResponse<UserLoginResult> response = new BaseResponse<>();
        UserLoginResult result = new UserLoginResult();
        response.setResult(result);

        String wxappOpenId = WxappUtil.getOpenId(code);

        if (wxappOpenId!=null){
            String token = userMapper.getTokenByWxappOpenId(wxappOpenId);
            if (token==null){
                // 生成临时token
                // 把token暂存在数据库
                UUID uuid = UUID.randomUUID();
                token = uuid.toString();

                User user = new User();
                user.setToken(token);
                user.setWxappOpenId(wxappOpenId);
                userMapper.insetUser(user);
            }
            response.setResponseState(ResponseState.SUCCESS);
            result.setToken(token);
        }else {
            // 获取微信小程序openid失败
            response.setResponseState(ResponseState.GET_WXAPP_OPEN_ID_FAILED);
        }

        return response;
    }

}
